package com.eylsun.simple_http

import io.vertx.core.AbstractVerticle
import io.vertx.core.Promise
import io.vertx.core.impl.logging.LoggerFactory

class MainVerticle : AbstractVerticle() {
  val LOG = LoggerFactory.getLogger(MainVerticle::class.java)
  val start = "======= ======= =======\r\n"
  val end = "----: ------- ------- -------\r\n"

  override fun start(startPromise: Promise<Void>) {
    vertx.createHttpServer().requestHandler { req ->
      req.body { ar ->

        val content = ar.result().toString("UTF-8")
        if (ar.succeeded()) {

          var reply = start + "succeeded ${
            req.remoteAddress().toString()
          } -> ${req.method()}:${req.path()}${if (req.query() == null) "" else "?${req.query()}"}\r\n${
            req.headers().joinToString("\r\n")
          }${if (content == null || content.isEmpty()) "" else "\r\n\r\n${content}"}"

          reply = reply + "\r\n" + end
          LOG.info(reply)

          req.response().putHeader("content-type", "text/html").end(reply.replace("\r\n", "\r\n<br>"))

        } else {

          var reply = start + "   failed ${
            req.remoteAddress().toString()
          } -> ${req.method()}:${req.path()}${if (req.query() == null) "" else "?${req.query()}"}\r\n${
            req.headers().joinToString("\r\n")
          }${if (content == null || content.isEmpty()) "" else "\r\n\r\n${content}"}"

          reply = reply + "\r\n" + end
          LOG.error(reply, ar.cause())

          req.response().putHeader("content-type", "text/html").end(reply.replace("\r\n", "\r\n<br>"))
        }

      }


    }.listen(18888).onComplete { http ->
      if (http.succeeded()) {
        startPromise.complete()
        println("HTTP server started on port 18888")
      } else {
        startPromise.fail(http.cause())
      }
    }
  }
}
